<!-- src/view/productionOrder.vue -->
<template>
  <div class="production-order-container">
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="100px" inline>
        <el-form-item label="状态">
          <el-input v-model="searchForm.status" placeholder="请输入状态" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchOrders">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card>
      <template #header>
        <div class="card-header">
          <span>生产订单列表</span>
          <el-button type="primary" @click="handleAdd">新增订单</el-button>
        </div>
      </template>

      <el-table :data="tableData" border stripe>
        <el-table-column prop="id" label="订单ID" width="80" />
        <el-table-column prop="productId" label="产品ID" width="100" />
        <el-table-column prop="quantity" label="数量" width="100" />
        <el-table-column prop="startDate" label="开始日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.startDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="endDate" label="结束日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.endDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="500px"
        @close="handleDialogClose"
    >
      <el-form
          ref="orderFormRef"
          :model="orderForm"
          :rules="orderRules"
          label-width="100px"
      >
        <el-form-item label="产品ID" prop="productId">
          <el-input v-model.number="orderForm.productId" />
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input v-model.number="orderForm.quantity" />
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker
              v-model="orderForm.startDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择开始日期"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker
              v-model="orderForm.endDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择结束日期"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-input v-model="orderForm.status" placeholder="请输入状态" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitOrder">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<!-- src/view/productionOrder.vue -->
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import productionOrderApi from '@/api/productionOrderApi'

// 搜索表单
const searchForm = reactive({
  status: ''
})

// 表格数据
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 表单数据
const orderForm = reactive({
  id: null,
  productId: null,
  quantity: null,
  startDate: '',
  endDate: '',
  status: ''
})

// 表单验证规则
const orderRules = {
  productId: [
    { required: true, message: '请输入产品ID', trigger: 'blur' },
    { type: 'number', message: '产品ID必须为数字', trigger: 'blur' }
  ],
  quantity: [
    { required: true, message: '请输入数量', trigger: 'blur' },
    { type: 'number', message: '数量必须为数字', trigger: 'blur' }
  ],
  startDate: [
    { required: true, message: '请选择开始日期', trigger: 'change' }
  ],
  endDate: [
    { required: true, message: '请选择结束日期', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请输入状态', trigger: 'blur' }
  ]
}

// 表单引用
const orderFormRef = ref(null)

// 日期格式化函数
const formatDate = (date) => {
  if (!date) return ''
  // 处理字符串格式的日期
  if (typeof date === 'string') {
    // 如果是完整日期时间格式，则只取日期部分
    if (date.includes(' ')) {
      return date.split(' ')[0]
    }
    return date
  }
  // 处理Date对象
  if (date instanceof Date) {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  }
  return String(date)
}

// 生命周期
onMounted(() => {
  loadOrders()
})

// 加载订单列表
const loadOrders = async () => {
  try {
    // 构造分页参数
    const pageParams = {
      page: currentPage.value,
      limit: pageSize.value
    }

    const res = await productionOrderApi.page(pageParams, searchForm)

    console.log('生产订单响应数据:', res)

    // 处理后端返回的实际格式 {code: 200, msg: '', data: {data: [...], count: ...}}
    if (res && res.code === 200 && res.data) {
      // 修改这里：使用 data 而不是 list，使用 count 而不是 total
      tableData.value = Array.isArray(res.data.data) ? res.data.data : []
      total.value = res.data.count || 0
    } else {
      tableData.value = []
      total.value = 0
    }
  } catch (err) {
    console.error('加载生产订单失败:', err)
    ElMessage.error('加载生产订单失败: ' + (err.message || ''))
    tableData.value = []
    total.value = 0
  }
}

// 搜索
const searchOrders = () => {
  currentPage.value = 1
  loadOrders()
}

// 重置搜索
const resetSearch = () => {
  searchForm.status = ''
  currentPage.value = 1
  loadOrders()
}

// 处理新增
const handleAdd = () => {
  dialogTitle.value = '新增生产订单'
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑生产订单'
  isEdit.value = true
  // 映射后端字段到前端表单字段
  Object.assign(orderForm, {
    id: row.id,
    productId: row.productId,
    quantity: row.quantity,
    startDate: row.startDate,
    endDate: row.endDate,
    status: row.status
  })
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
      `确定要删除订单ID为 ${row.id} 的生产订单吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    try {
      const res = await productionOrderApi.del(row.id)
      if (res && res.code === 200) {
        ElMessage.success('删除成功')
        loadOrders()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (err) {
      console.error('删除失败:', err)
      ElMessage.error('删除失败: ' + (err.message || ''))
    }
  }).catch(() => {
    // 取消删除
  })
}

// 提交表单
const submitOrder = () => {
  orderFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res
        if (isEdit.value) {
          res = await productionOrderApi.edit(orderForm)
        } else {
          res = await productionOrderApi.add(orderForm)
        }

        if (res && res.code === 200) {
          ElMessage.success(`${isEdit.value ? '编辑' : '新增'}成功`)
          dialogVisible.value = false
          loadOrders()
        } else {
          ElMessage.error(res.msg || `${isEdit.value ? '编辑' : '新增'}失败`)
        }
      } catch (err) {
        console.error(`${isEdit.value ? '编辑' : '新增'}失败:`, err)
        ElMessage.error(`${isEdit.value ? '编辑' : '新增'}失败: ` + (err.message || ''))
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  Object.assign(orderForm, {
    id: null,
    productId: null,
    quantity: null,
    startDate: '',
    endDate: '',
    status: ''
  })

  // 清除表单验证
  if (orderFormRef.value) {
    orderFormRef.value.resetFields()
  }
}

// 关闭对话框
const handleDialogClose = () => {
  resetForm()
}

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  loadOrders()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadOrders()
}
</script>


<style scoped>
.production-order-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
